import store from './store.js';
import { random } from './helper.js';

/**
 * Router Handler
 */
function handler (router) {
    /**
     * 获取当前路由的页面数据
     */
    const getPageData = function (component) {
        return store.getPageData(component?.$route?.query?.navKey);
    };

    /**
     * 后退路由
     */
    const back = function ({ params }) {
        store.delPageStackLen();
        store.changeBackFlag(true);

        if (params) {
            store.changeBackData(params);
        } else {
            store.clearBackData();
        }

        router.back();
    };

    /**
     * 前进路由
     */
    const push = function ({ path, name, params, query }) {
        const navKey = random(6);
        query = Object.assign(Object.create(null), { navKey, isBack: false }, query);

        store.addPageStackLen();

        if (path) {
            store.changePathData(params);
            router.push({ path, query });
        }
        if (name) {
            router.push({ name, query });
        }
    };

    /**
     * 替换路由
     */
    const replace = function ({ path, name, params, query }) {
        const navKey = random(6);
        query = Object.assign(Object.create(null), { navKey, isBack: false }, query);

        if (path) {
            store.changePathData(params);
            router.replace({ path, query });
        }
        if (name) {
            router.replace({ name, query });
        }
    };

    /**
     * “穿越”路由
     */
    const go = function (n) {
        if (n > 0) {
            store.addPageStackLen(n);
        } else {
            store.delPageStackLen(n);
            store.changeBackFlag(true);
        }

        router.go(n);
    };

    /**
     * 跳转至“首页”
     */
    const backReferPage = function () {
        go(-(store.state.pageStackLen - 1));
    };

    return { back, push, replace, go, backReferPage, getPageData };
}

export default handler;
